#coding=utf-8
import datetime
from stock import TradableShare, Stock, SIndex
from eday import Eday
from price import Price
from django.core.exceptions import ObjectDoesNotExist

class UnknownFinanceToolError(Exception):
    def __init__(self, finance_tool):
        self.finance_tool = finance_tool
    def __str__(self):
        return  'Unknown finance tool:%s'%type(self.finance_tool)
         
def get_stock_by_code(code):
    try:
        s = Stock.objects.get(code=code)
        return s
    except Stock.DoesNotExist:
        return None
        
def get_or_create_stock(code):
    s = get_stock_by_code(code)
    if s:
        return s
        
    from stockcrawler import get_stock
    data = get_stock(code)
    s = Stock.objects.get_or_create(**data)[0]
    s.update_ts()
    return s

def update_edays(finance_tool):
    f = finance_tool
    
    t = ''
    if isinstance(f, Stock):
        t = 'stock'
    elif isinstance(f, SIndex):
        t = 'sindex'
    else:
        raise UnknownFinanceToolError(f)
    
    code = f.code
    pre = None
    from stockcrawler import get_prices_between
    
    e = f.latest_day
    if not e:
        if t == 'stock':
            start = f.ipo.isoformat()
        else:
            start = f.start_on.isoformat()
    elif e == datetime.date.today():
        return 
    else:
        pre = e
        
        delta = datetime.timedelta(days=1)
        start = e.date + delta
        start = start.isoformat()
        
    ps = get_prices_between(code, start, fins=t)
    
    for p in ps:
        e = Eday(date=p.date, finance_tool=f)
        if pre:e.pre = pre
        e.save()
        pre = e
        
        price = Price(eday=e)
        price.start = p.open; price.end = p.close
        price.high = p.highest; price.low = p.lowest
        price.volume = p.volume; price.amount = p.amount
        
        price.save()
